<template>
  <div class="article-list" ref="articleList" @scroll="scrollEvent">
    <van-pull-refresh v-model="isLoading" @refresh="refresh">
      <van-list
        v-if="bol"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多数据了!"
        @load="getData"
      >
        <article-item :item="i" v-for="i in list" :key="i.art_id" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import ArticleItem from './article-item.vue'
import { articlesGet } from '@/api/home.js'
export default {
  name: 'ArticleList',
  props: ['id'],
  components: {
    ArticleItem
  },
  data () {
    return {
      bol: true,
      isLoading: false,
      loading: false,
      finished: false,
      list: [],
      timestamp: Date.now(),
      scrollTop: 0
    }
  },
  created () {
    // this.getData()
  },
  methods: {
    async getData () {
      const res = await articlesGet({
        channel_id: this.id,
        timestamp: this.timestamp
      })
      //   数据累加处理
      this.list.push(...res.data.results)
      this.loading = false
      // 如果返回值的时间戳有值说明有下一页,存储调用下一页,没值加载完成了
      if (res.data.pre_timestamp) {
        this.timestamp = res.data.pre_timestamp
      } else {
        this.finished = true
      }
      console.log('列表数据:', res)
    },
    //   下拉刷新
    async refresh () {
      // list组件的属性还原
      this.loading = false
      this.finished = false
      // 调用第一页数据,时间戳还原
      this.timestamp = Date.now()
      this.list = []
      // 加入await 保证接口调用完成后做下一步
      await this.getData()
      this.isLoading = false
      // 将组件初始化一次
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    },
    // 滚动事件
    scrollEvent () {
      // 滚动事件记录滚动位置
      this.scrollTop = this.$refs.articleList.scrollTop
    }
  },
  activated () {
    // 获取dom
    this.$refs.articleList.scrollTop = this.scrollTop // 还原滚动位置
  },
  deactivated () {}
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
